package com.smilive.start.netty.jdk;

import com.smilive.start.netty.utils.ByteBufferUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * @program: netty_start
 * @Date: 2022-01-04 16:44
 * @Author: smilive
 * @Description:
 */
@Slf4j
public class Worker implements Runnable {

    private Thread thread;
    private Selector selector;
    private String name;
    private volatile boolean started = false;

    private static ConcurrentLinkedQueue<Runnable> queue = new ConcurrentLinkedQueue<>();

    public Worker(String name) {
        this.name = name;
    }

    public void init(SocketChannel socketChannel) throws IOException {
        if (!started){
            thread = new Thread(this, name);
            selector = Selector.open();
            thread.start();
            started = true;
        }
        queue.add(() ->{
            try {
                socketChannel.register(selector,SelectionKey.OP_READ);
            } catch (ClosedChannelException e) {
                e.printStackTrace();
            }
        });
        //唤醒select线程,让worker线程获取得到select执行注册读事件
        selector.wakeup();
    }

    @Override
    public void run() {
        while (true){
            try {
                selector.select();
                Runnable task = queue.poll();
                if (task != null){
                    task.run();
                }
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()){
                    SelectionKey key = iterator.next();
                    iterator.remove();

                    //只处理读事件
                    if (key.isReadable()){
                        SocketChannel channel = (SocketChannel) key.channel();
                        ByteBuffer buffer = ByteBuffer.allocate(16);
                        channel.read(buffer);
                        buffer.flip();
                        log.debug("{}:收到消息",channel);
                        ByteBufferUtil.debugAll(buffer);
                    }
                }


            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
